from datetime import date

from rest_framework import status
from rest_framework.generics import ListAPIView, CreateAPIView, RetrieveAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from fdfs_client.client import Fdfs_client
from goods.models import SKUImage, SKU, GoodsVisitCount, GoodsCategory, Goods, GoodsSpecification
from meiduo_admin.serializers.skus import ImageSeriazlier, SKUSeriazlier, SKUCountSerializer, \
    SKUCategorieSerializer, GoodsSimpleSerializer, GoodsSpecSerialzier
from rest_framework.viewsets import ModelViewSet
from django.conf import settings
from meiduo_admin.utils import PageNum


# sku列表
class SKUView(ListAPIView):

    queryset = SKU.objects.all().order_by('id')
    serializer_class = SKUSeriazlier


# 图片管理
class ImageView(ModelViewSet):
    queryset = SKUImage.objects.all().order_by('id')
    serializer_class = ImageSeriazlier
    pagination_class = PageNum

    # 重写拓展类的保存业务逻辑
    def create(self, request, *args, **kwargs):
        # 提取数据
        sku_id = request.data.get('sku')
        img_bin = request.FILES.get("image").read()

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(img_bin)

        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)

        # 获取上传后的路径
        image_url = res['Remote file_id']

        # 保存图片
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)

        return Response({'id': img.id, "sku": sku_id, 'image': image_url}, status=status.HTTP_201_CREATED)

    # 重写拓展类的保存业务逻辑
    def update(self, request, *args, **kwargs):
        # 提取数据
        sku_id = request.data.get('sku')
        img_bin = request.FILES.get("image").read()

        # 创建FastDFS连接对象
        client = Fdfs_client(settings.FDFS_CLIENT_CONF)
        # 上传图片到fastDFS
        res = client.upload_by_buffer(img_bin)

        if res['Status'] != 'Upload successed.':
            return Response(status=status.HTTP_403_FORBIDDEN)

        # 获取上传后的路径
        image_url = res['Remote file_id']

        # 修改图片
        img = SKUImage.objects.filter(id=kwargs['pk']).update(image=image_url)

        return Response({'id': kwargs['pk'], "sku": sku_id, 'image': image_url}, status=status.HTTP_201_CREATED)


# 统计分类商品访问量
class SKUCountView(APIView):
    # 获取当前日期
    now_date = date.today()

    def post(self, request, *args, **kwargs):
        # 设置查询集
        queryset = GoodsVisitCount.objects.filter(date=self.now_date, category_id=kwargs['category_id']).count()

        if queryset:
            # 更新数据
            good_obj = GoodsVisitCount.objects.get(date=self.now_date, category_id=kwargs['category_id'])
            good_obj.count += 1
            good_obj.save()
        else:
            # 添加数据
            GoodsVisitCount.objects.create(date=self.now_date, category_id=kwargs['category_id'], count=1)

        return Response({'code': 0, 'errmsg': 'OK'})


# 实现日分类商品访问量
class SKUDailyIncrementCountView(APIView):

    # 管理员权限
    # permission_classes = [IsAdminUser]

    def get(self, request):
        # 获取当前日期
        now_date = date.today()
        # 设置查询集
        queryset = GoodsVisitCount.objects.filter(date__gte=now_date, count__gt=0).order_by('id')

        data = []
        for category in queryset:
            category_obj = GoodsCategory.objects.get(id=category.id)

            # 获取数据
            count = category.count

            data.append({'count': count, "category": category_obj.name})

        return Response(data)


# 获取SKU三级分类信息
class SKUCategoriesView(ListAPIView):
    serializer_class = SKUCategorieSerializer
    queryset = GoodsCategory.objects.filter(goodscategory=None)


# 获取SPU表名称数据
class GoodsSimpleView(ListAPIView):
    serializer_class = GoodsSimpleSerializer
    queryset = Goods.objects.all()


# 获取SPU商品规格信息
class GoodsSpecView(ListAPIView):
    serializer_class = GoodsSpecSerialzier

    def get_queryset(self):
        sku_id = self.kwargs['pk']
        return GoodsSpecification.objects.filter(spu_id=sku_id)

